package com.example.sqliteviewer;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

public class CreateTableActivity extends AppCompatActivity {

    private String databasePath;
    private SQLiteDatabase database;
    private EditText etTableName;
    private LinearLayout fieldsContainer;

    // 数据类型选项
    private final String[] dataTypes = {"INTEGER", "TEXT", "REAL", "BLOB", "NUMERIC"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_table);

        databasePath = getIntent().getStringExtra("DATABASE_PATH");
        if (databasePath == null) {
            Toast.makeText(this, "数据库路径无效", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        setTitle("创建新表");

        // 初始化视图
        etTableName = findViewById(R.id.etTableName);
        fieldsContainer = findViewById(R.id.fieldsContainer);
        Button btnAddField = findViewById(R.id.btnAddField);
        Button btnCreateTable = findViewById(R.id.btnCreateTable);

        // 添加字段按钮点击事件
        btnAddField.setOnClickListener(v -> addFieldView());

        // 创建表按钮点击事件
        btnCreateTable.setOnClickListener(v -> createTable());

        // 添加第一个字段视图
        addFieldView();
    }

    private void addFieldView() {
        View fieldView = LayoutInflater.from(this).inflate(R.layout.item_field, fieldsContainer, false);

        // 初始化字段类型下拉框
        Spinner spinnerType = fieldView.findViewById(R.id.spinnerType);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, dataTypes);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerType.setAdapter(adapter);

        // 删除字段按钮
        Button btnRemove = fieldView.findViewById(R.id.btnRemoveField);
        btnRemove.setOnClickListener(v -> {
            if (fieldsContainer.getChildCount() > 1) {
                fieldsContainer.removeView(fieldView);
            } else {
                Toast.makeText(this, "至少需要一个字段", Toast.LENGTH_SHORT).show();
            }
        });

        fieldsContainer.addView(fieldView);
    }

    private void createTable() {
        String tableName = etTableName.getText().toString().trim();
        if (TextUtils.isEmpty(tableName)) {
            Toast.makeText(this, "请输入表名", Toast.LENGTH_SHORT).show();
            return;
        }

        // 收集字段信息
        List<FieldInfo> fields = new ArrayList<>();
        boolean hasPrimaryKey = false;

        for (int i = 0; i < fieldsContainer.getChildCount(); i++) {
            View fieldView = fieldsContainer.getChildAt(i);
            EditText etFieldName = fieldView.findViewById(R.id.etFieldName);
            Spinner spinnerType = fieldView.findViewById(R.id.spinnerType);
            CheckBox cbPrimaryKey = fieldView.findViewById(R.id.cbPrimaryKey);
            CheckBox cbNotNull = fieldView.findViewById(R.id.cbNotNull);
            CheckBox cbAutoIncrement = fieldView.findViewById(R.id.cbAutoIncrement);

            String fieldName = etFieldName.getText().toString().trim();
            if (TextUtils.isEmpty(fieldName)) {
                Toast.makeText(this, "字段名不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            FieldInfo field = new FieldInfo();
            field.name = fieldName;
            field.type = spinnerType.getSelectedItem().toString();
            field.isPrimaryKey = cbPrimaryKey.isChecked();
            field.isNotNull = cbNotNull.isChecked();
            field.isAutoIncrement = cbAutoIncrement.isChecked();

            if (field.isPrimaryKey) {
                hasPrimaryKey = true;
            }

            fields.add(field);
        }

        if (!hasPrimaryKey) {
            new AlertDialog.Builder(this)
                    .setTitle("警告")
                    .setMessage("当前没有设置主键，是否继续创建表？")
                    .setPositiveButton("继续", (dialog, which) -> executeCreateTable(tableName, fields))
                    .setNegativeButton("取消", null)
                    .show();
        } else {
            executeCreateTable(tableName, fields);
        }
    }

    private void executeCreateTable(String tableName, List<FieldInfo> fields) {
        try {
            database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);

            // 构建CREATE TABLE语句
            StringBuilder sql = new StringBuilder();
            sql.append("CREATE TABLE ").append(tableName).append(" (");

            for (int i = 0; i < fields.size(); i++) {
                FieldInfo field = fields.get(i);
                if (i > 0) {
                    sql.append(", ");
                }

                sql.append(field.name).append(" ").append(field.type);

                if (field.isPrimaryKey) {
                    sql.append(" PRIMARY KEY");
                    if (field.isAutoIncrement && field.type.equals("INTEGER")) {
                        sql.append(" AUTOINCREMENT");
                    }
                }

                if (field.isNotNull) {
                    sql.append(" NOT NULL");
                }
            }

            sql.append(")");

            // 执行SQL语句
            database.execSQL(sql.toString());

            Toast.makeText(this, "表创建成功", Toast.LENGTH_SHORT).show();
            setResult(RESULT_OK);
            finish();

        } catch (Exception e) {
            Toast.makeText(this, "创建表失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        } finally {
            if (database != null && database.isOpen()) {
                database.close();
            }
        }
    }

    private static class FieldInfo {
        String name;
        String type;
        boolean isPrimaryKey;
        boolean isNotNull;
        boolean isAutoIncrement;
    }
}